import {ref, watch} from 'vue'
import {useModal} from '../composables/useModal'
import type {Package} from '../types'
import {API_URL} from '../config/apiConfig'
import {addAuthHeader} from './api/apiUtils'
import {fetchWithTimeout} from "../utils/request.ts";

interface Rule {
    id: string
    ruleFileName: string
}

export function useInspectionModal(
    props: { show: boolean },
    emit: any,
    fetchRecords: () => Promise<void>
) {
    const {modalContentStyle, openModal: originalOpenModal, closeModal, handleModalClick} = useModal()

    const openModal = () => {
        originalOpenModal()
        fetchRules() // 每次打开模态框时刷新规则列表
        fetchRecords()
    }

    const selectedFile = ref<File | null>(null)
    const fileType = ref('')
    const procurementMethod = ref('open')
    const customRuleSet = ref('')
    const rules = ref<Rule[]>([])
    const loadingRules = ref(false)
    const packages = ref<Package[]>([
        {
            id: 1,
            pricingMethod: 'TotalPrice',
            packageType: 'SERVICE',
            sme: false,
            acceptJointResponse: false
        }
    ])
    const activeTab = ref('records')

    const tabs = [
        {id: 'records', name: '检验记录'},
        {id: 'annotations', name: '标注表'}
    ]

    watch(() => props.show, (newShow) => {
        if (newShow) {
            openModal()
        }
    })

    const closeModalHandler = () => {
        closeModal(emit)
    }

    const handleModalClickHandler = (e: Event) => {
        handleModalClick(e, emit)
    }

    const addPackage = () => {
        const newId = Math.max(...packages.value.map(p => p.id)) + 1
        packages.value.push({
            id: newId,
            pricingMethod: 'TotalPrice',
            packageType: 'SERVICE',
            sme: false,
            acceptJointResponse: false
        })
    }

    const removePackage = (index: number) => {
        if (packages.value.length > 1) {
            packages.value.splice(index, 1)
        } else {
            alert('至少需要保留一个采购包')
        }
    }

    const updatePackage = (index: number, data: Partial<Package>) => {
        packages.value[index] = {...packages.value[index], ...data}
    }

    const fetchRules = async () => {
        loadingRules.value = true
        try {
            const response = await fetch(`${API_URL}/demo/rule/list`, addAuthHeader(
                {
                    credentials: 'include',
                    method: 'GET'
                }
            ))
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`)
            }
            rules.value = await response.json()
        } catch (err) {
            console.error('获取规则列表失败:', err)
        } finally {
            loadingRules.value = false
        }
    }

    const inspecting = ref(false)

    const startInspection = async () => {
        if (!selectedFile.value) {
            alert('请上传文件')
            return
        }

        if (!fileType.value) {
            alert('请选择文件类型')
            return
        }

        if (packages.value.length === 0) {
            alert('请添加采购包')
            return
        }

        const formData = new FormData()
        formData.append('file', selectedFile.value)
        if (customRuleSet.value) {
            formData.append('ruleId', customRuleSet.value)
            
            // 将采购包参数转换为 JSON 字符串
            const purchasePackageParams = packages.value.map(pkg => ({
                isSmeTargeted: Boolean(pkg.sme),
                quoteMethod: pkg.pricingMethod,
                acceptJointResponse: Boolean(pkg.acceptJointResponse),
                packageType: pkg.packageType
            }))
            
            formData.append('purchasePackageParams', JSON.stringify(purchasePackageParams))
        }

        inspecting.value = true
        try {
            const response = await fetchWithTimeout(`${API_URL}/demo/compare`, addAuthHeader({
                method: 'POST',
                body: formData
            }), 60000 * 5)
            // const response = await fetch(`${API_URL}/demo/compare`, addAuthHeader({
            //   method: 'POST',
            //   body: formData
            // }))

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`)
            }

            alert('文档检验已完成！请查看检验记录获取结果。')
            await fetchRecords()
        } catch (err) {
            console.error('文档检验失败:', err)
            alert('文档检验失败，请稍后重试')
        } finally {
            inspecting.value = false
        }
    }

    return {
        modalContentStyle,
        selectedFile,
        fileType,
        procurementMethod,
        customRuleSet,
        rules,
        loadingRules,
        packages,
        activeTab,
        tabs,
        inspecting,
        closeModal: closeModalHandler,
        handleModalClick: handleModalClickHandler,
        addPackage,
        removePackage,
        updatePackage,
        startInspection
    }
}
